package com.ruoyi.web.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.business.entity.YytMember;
import com.ruoyi.common.business.entity.YytMemberReceiveAddress;
import com.ruoyi.common.business.service.YytMemberReceiveAddressService;
import com.ruoyi.common.business.service.YytMemberService;
import com.ruoyi.common.sms.service.YytActActivityService;
import com.ruoyi.common.sms.service.YytSmsCouponService;
import com.ruoyi.config.AppConfig;
import com.ruoyi.utils.*;
import com.ruoyi.vo.FindPasswordVo;
import com.ruoyi.vo.RegisterVo;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.UUID;

/**
 * @ClassName MemberController
 * @Description
 * @Author huangshun
 * @Date 2021/12/18 17:08
 */
@RequestMapping("user")
@RestController
public class MemberController {

    @Autowired
    private RedisService redisService;
    @Autowired
    private YytMemberService yytMemberService;
    @Autowired
    private YytActActivityService yytActActivityService;
    @Autowired
    private YytSmsCouponService yytSmsCouponService;
    @Autowired
    private YytMemberReceiveAddressService yytMemberReceiveAddressService;

    /**
     * 方法名 getUserInfo
     * 描述 TODO 获取登录用户信息
     * 作者 黄顺
     * 时间 2021/12/18 17:24
     *
     * @Param []
     */
    @GetMapping("getUserInfo")
    public ResponseResult getUserInfo() {
        String loginIdAsString = StpUtil.getLoginIdAsString();
        JSON parse = JSONUtil.parse(redisService.get(loginIdAsString));
        YytMember yytMember = BeanUtil.toBean(parse, YytMember.class);
        return ResponseResult.success(yytMemberService.getById(yytMember.getId()));
    }

    /**
     * 方法名 register
     * 描述 TODO 用户注册
     * 作者 黄顺
     * 时间 2021/12/18 17:25
     *
     * @Param []
     */
    @PostMapping("register")
    public ResponseResult register(@RequestBody RegisterVo registerVo) {
        if (registerVo != null) {
            Object o = redisService.get(registerVo.getCodeKey());
            if (o == null) {
                return ResponseResult.failure("验证码已过期!");
            }
            if (!registerVo.getCode().equals(String.valueOf(o))) {
                return ResponseResult.failure("验证码输入不正确!");
            }
            int count = 0;
            LambdaQueryWrapper<YytMember> yytMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
            yytMemberLambdaQueryWrapper.eq(YytMember::getUsername, registerVo.getUserName()).eq(YytMember::getDelFlag, "0");
            count = yytMemberService.count(yytMemberLambdaQueryWrapper);
            if (count > 0) {
                return ResponseResult.failure("用户名已存在!");
            }
            yytMemberLambdaQueryWrapper.clear();
            yytMemberLambdaQueryWrapper.eq(YytMember::getPhone, registerVo.getPhoneNumber()).eq(YytMember::getDelFlag, "0");
            count = yytMemberService.count(yytMemberLambdaQueryWrapper);
            if (count > 0) {
                return ResponseResult.failure("此手机号已注册!");
            }
            redisService.delete(registerVo.getCodeKey());
            QueryWrapper<YytMember> wrapper = new QueryWrapper<>();
            wrapper.eq("wechat_id", registerVo.getWechatId());
            YytMember one = yytMemberService.getOne(wrapper);

            //生成加密盐
            String salt = WebConstants.generateNumber();
            SaSecureUtil.md5(salt);
            YytMember yytMember = new YytMember();
//            yytMember.setUsername(registerVo.getUserName());

            // md5加盐加密: md5(md5(str) + md5(salt))
//            yytMember.setPassword(SaSecureUtil.md5BySalt(registerVo.getPassword(), salt));
            yytMember.setSalt(salt);
            yytMember.setPhone(registerVo.getPhoneNumber());
            yytMember.setStatus("0");
            yytMember.setDelFlag("0");
            yytMember.setCreateBy(registerVo.getUserName());
            yytMember.setCreateTime(LocalDateTime.now());
            yytMember.setWechatId(registerVo.getWechatId());
            if(one == null){
                yytMember.setNickname(yytMember.getUsername());
                yytMemberService.save(yytMember);
            }else{
                yytMember.setId(one.getId());
                yytMemberService.updateById(yytMember);
            }
            return ResponseResult.success("注册成功");
        }
        return ResponseResult.failure("注册失败");
    }


    /**
     * 方法名 findPassword
     * 描述 TODO
     * 作者 黄顺
     * 时间 2021/12/20 10:30
     *
     * @Param [registerVo]
     */
    @PostMapping("findPassword")
    public ResponseResult findPassword(@RequestBody FindPasswordVo findPasswordVo) {
        Object o = redisService.get(findPasswordVo.getCodeKey());
        if (o == null) {
            return ResponseResult.failure("验证码已过期!");
        }
        if (!findPasswordVo.getCode().equals(String.valueOf(o))) {
            return ResponseResult.failure("验证码输入不正确!");
        }
        try {
            LambdaQueryWrapper<YytMember> yytMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
            yytMemberLambdaQueryWrapper.eq(YytMember::getPhone, findPasswordVo.getPhoneNumber()).eq(YytMember::getDelFlag, "0");
            YytMember yytMember = yytMemberService.getOne(yytMemberLambdaQueryWrapper);
            yytMember.setPassword(SaSecureUtil.md5BySalt(findPasswordVo.getNewPassword(), yytMember.getSalt()));
            yytMemberService.updateById(yytMember);
        } catch (Exception e) {
            return ResponseResult.success("操作失败");
        }

        return ResponseResult.success("操作成功");
    }

    /**
     * 用户保存收货地址
     */
    @PostMapping("/saveReceiveAddress")
    public ResponseResult saveReceiveAddress(@RequestBody YytMemberReceiveAddress receiveAddress) {
        YytMember loginUser = LoginUtils.getLoginUser(redisService);
        // 查找数据库中是否已有默认地址
        if ("0".equals(receiveAddress.getDefaultStatus())) {
            YytMemberReceiveAddress defaultAddress = yytMemberReceiveAddressService.getDefaultAddress(loginUser.getId());
            // 地址是否不为null且与当前保存地址不为同一地址
            if (null != defaultAddress && !defaultAddress.getId().equals(receiveAddress.getId())) {
                defaultAddress.setDefaultStatus("1");
                yytMemberReceiveAddressService.updateById(defaultAddress);
            }
        }
        receiveAddress.setMemberId(loginUser.getId());
        if (StringUtils.isNotBlank(receiveAddress.getId())) {
            yytMemberReceiveAddressService.updateById(receiveAddress);
        } else {
            yytMemberReceiveAddressService.save(receiveAddress);
        }
        return ResponseResult.success();
    }

    /**
     * 用户删除收货地址
     */
    @PostMapping("/delReceiveAddress")
    public ResponseResult delReceiveAddress(@RequestBody YytMemberReceiveAddress receiveAddress) {
        return ResponseResult.success(yytMemberReceiveAddressService.removeById(receiveAddress.getId()));
    }

    /**
     * 获取用户收货地址列表
     */
    @GetMapping("/getReceiveAddressList")
    public ResponseResult getReceiveAddressList() {
        return ResponseResult.success(yytMemberReceiveAddressService.list(new LambdaQueryWrapper<YytMemberReceiveAddress>()
                .eq(YytMemberReceiveAddress::getMemberId, LoginUtils.getLoginUser(redisService).getId())
                .orderByAsc(YytMemberReceiveAddress::getDefaultStatus)));
    }

    /**
     * 根据id获取用户收货地址
     */
    @GetMapping("/getReceiveAddress")
    public ResponseResult getReceiveAddress(@RequestParam("id") String addressId) {
        return ResponseResult.success(yytMemberReceiveAddressService.getById(addressId));
    }

    /**
     * 名字、修改密码
     */
    @PostMapping("/setUser")
    public ResponseResult setUser(@RequestBody HashMap<String,String> map, HttpServletRequest request){
        String loginIdAsString = StpUtil.getLoginIdAsString();
//        JSON parse = JSONUtil.parse(redisService.get(loginIdAsString));
//        YytMember yytMember = BeanUtil.toBean(parse, YytMember.class);
//        return ResponseResult.success(yytMember);
        LambdaQueryWrapper<YytMember> yytMemberLambdaQueryWrapper = new LambdaQueryWrapper<>();
        yytMemberLambdaQueryWrapper.eq(YytMember::getId,map.get("id")).eq(YytMember::getDelFlag,"0");
        YytMember member = yytMemberService.getOne(yytMemberLambdaQueryWrapper);
        String type = map.get("type");
        YytMember yytMember = new YytMember();
        yytMember.setId(map.get("id"));
        if (type.equals("nickname")) {
            String nickname = map.get("nickname");
            yytMember.setNickname(nickname);
            member.setNickname(nickname);
            yytMemberService.updateById(yytMember);
        }
        if (type.equals("password")){
            String password=map.get("password");
            // md5加盐加密: md5(md5(str) + md5(salt))
            password = SaSecureUtil.md5BySalt(password, member.getSalt());
            yytMember.setPassword(password);
            member.setPassword(password);
            yytMemberService.updateById(yytMember);
        }
        redisService.putNoTime(member.getId(), JSONUtil.toJsonPrettyStr(member));
        return ResponseResult.success("修改成功！");

    }

    /**
     * 修改头像
     */
    //处理文件上传
    @RequestMapping(value="/image", method = RequestMethod.POST)
    public @ResponseBody ResponseResult uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request){

        String fileName = UUID.randomUUID().toString();
        String extension = "." + FilenameUtils.getExtension(file.getOriginalFilename());
        String filePath = fileName + "" + extension;
        //设置文件上传路径
//        String filePath = request.getSession().getServletContext().getRealPath("imgupload/");
        try {
            //FileUtil.uploadFile(file.getBytes(), AppConfig.getProfile() + "/", fileName);
            String path = AliCosUtils.uploadFile(file, "yytfile/user/photo/" + filePath);
            String id = request.getParameter("id");
            String url = request.getParameter("url");
            YytMember yytMember = new YytMember();
            yytMember.setId(id);
            yytMember.setIcon(path);
            yytMemberService.updateById(yytMember);
            YytMember member = yytMemberService.getById(id);
            redisService.putNoTime(id, JSONUtil.toJsonPrettyStr(member));
            return ResponseResult.success((Object) yytMember.getIcon());
        } catch (Exception e) {
            return ResponseResult.failure("上传失败");
        }
    }


    @GetMapping("/getMyRebate")
    public ResponseResult getMyRebate(@RequestParam("memberId") String memberId){
        return ResponseResult.success(yytMemberService.getById(memberId));
    }

}
